// 获取用户信息
$.ajax({
    type: "get",
    url: "/userInfo",
    success: function(body) {
        let nameE = document.querySelector("#name");
        let coinE = document.querySelector("#coin");
        let winRateE = document.querySelector("#win_rate");
        let winCountE = document.querySelector("#win_count");
        let totalCountE = document.querySelector("#total_count");

        nameE.innerHTML = body.phoneNumber;
        coinE.innerHTML = body.coin;
        winRateE.innerHTML = body.winCount / body.totalCount;
        winCountE.innerHTML = body.winCount;
        totalCountE.innerHTML = body.totalCount;

        console.log(body.phoneNumber);
        console.log(body.coin);
        console.log(body.winCount);
        console.log(body.totalCount);
    },
    error: function() {
        alert("获取用户信息失败！");
    }
});


// 创建一个 WebSocket 对象，转换协议
let websocket = new WebSocket("ws://127.0.0.1:8082/findMatch");

// 设置各种情况下的前端工作台反馈
websocket.onopen = function() {
    console.log("onopen");
}
websocket.onclose = function() {
    console.log("onclose");
}
websocket.onerror = function() {
    console.log("onerror");
}

// 当浏览器里使用当前 websocket 连接的窗口被直接关闭时，提前断开 websocket 连接
window.onbeforeunload = function() {
    websocket.close();
}

// 当接收到信息的时候，调用该方法
websocket.onmessage = function(e) {
    let resp = JSON.parse(e.data);
    let matchButton = document.querySelector("#match_button");

    console.log(resp.message);
    if (!resp.ok) {
        console.log("游戏大厅中接收到了失败响应！" + resp.reason);
        return;
    }
    if (resp.message == "startMatch") {
        console.log("进入匹配队列成功！");
        matchButton.innerHTML = "停止匹配";
    } else if (resp.message == "stopMatch") {
        console.log("离开匹配队列成功！");
        matchButton.innerHTML = "开始匹配";
    } else if (resp.message == "matchSuccess") {
        console.log("匹配到对手！进入游戏房间！");
        location.assign("/room.html");
    } else {
        console.log("收到了非法的响应！message = " + resp.message);
    }
}

let matchButton = document.querySelector("#match_button");
matchButton.onclick = function() {
    if (websocket.readyState == websocket.OPEN) {
        if (matchButton.innerHTML == "开始匹配") {
            console.log("开始匹配!");
            websocket.send(JSON.stringify({
                message: "startMatch",
            }));
        } else if (matchButton.innerHTML == "停止匹配") {
            console.log("停止匹配");
            websocket.send(JSON.stringify({
                message: "stopMatch",
            }));
        }
    } else {
        alert("连接已断开！请重新登录");
        location.assign("/login.html");
    }
}